package org.webball.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;

import org.webball.base.interfaces.ICommunication;
import org.webball.base.interfaces.IList;
import org.webball.base.interfaces.IMessage;
import org.webball.communication.Communication;
import org.webball.tools.PlayersList;

public class TestClient {

	private ICommunication communication= null;
	private IMessage message= new Message();
	private IList list= new PlayersList();

	

	public void start(){

		IMessage message= new Message();
		try{
			communication= new Communication("localhost", 5466);
			communication.setMessage(message);
			communication.setPlayersList(list);
			communication.start();
			Reciver reciver= new Reciver(message, list, communication);
			reciver.start();
			BufferedReader reader= new BufferedReader(new InputStreamReader(System.in));
			String login= reader.readLine();
			communication.send(new Message(Message.LOGIN+login));

			boolean end= false;
			
			while(!end){
				String msg= reader.readLine();
				if(msg.equals("end")){
					end= true;
					reciver.setEnd(true);
				}
				else{
					communication.send(new Message(msg));
				}
			}
			reader.close();
			
			
		}
		catch(IOException e){
			e.printStackTrace();
		}
	}
	
	public static void main(String args[]){
		TestClient client= new TestClient();
		client.start();
	}
	
	private class Reciver extends Thread{
		private IMessage msg;
		private IList list;
		private List<String> curList;
		private boolean end= false;
		private ICommunication communication;
		public Reciver(IMessage msg, IList list, ICommunication communication){
			this.msg= msg;
			this.list= list;
			this.curList= new LinkedList<String>(list.getList());
			this.communication= communication;
			
		}
		public void run(){
			while(!interrupted()){
				if(!msg.getText().isEmpty()){
					System.out.println(msg.getText());
					msg.clear();
				}
				List<String> tmpList= new LinkedList<String>(list.getList());

				
				if(!tmpList.equals(curList)){
					System.out.println("Player list:");
					System.out.println("********************");

					for(String name : tmpList)
						System.out.println(name);
					curList= tmpList;
					System.out.println("*********************");
				}
				if(end){
					communication.send(new Message(Message.CLOSE));
					try {
						sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					communication.end();
					this.interrupt();
				}
				try {
					sleep(100);
				} catch (InterruptedException e) {
					this.interrupt();
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		public void setEnd(boolean end) {
			this.end = end;
		}
		
	}

}
